#  -*- coding: utf-8 -*-
# @Time    : 2020/11/19 21:14
# @Author  : 韋筠曦
# @Site    : 
# @File    : write_csv.py
# @Software: PyCharm


import csv


class Snippet:

    def __init__(self):
        self.f = open('filenames.csv', 'a', encoding='utf-8', newline='')  # 详情请看参考知识206行
        # 写入表头
        self.headers = ['class', 'name', 'sex', 'height', 'year']
        self.dictwirter = csv.DictWriter(self.f, self.headers)
        self.dictwirter.writeheader() # 写入表头

    def dosomething(self):
        '''
        写入字典数据到 csv 文件
        :return:
        '''
        dict_rows = [
            {'class': 1, 'name': 'xiaoming', 'sex': 'male', 'height': 168, 'year': 23},
            {'class': 1, 'name': 'xiaohong', 'sex': 'female', 'height': 162, 'year': 22},
            {'class': 2, 'name': 'xiaozhang', 'sex': 'female', 'height': 163, 'year': 21},
            {'class': 2, 'name': 'xiaoli', 'sex': 'male', 'height': 158, 'year': 21},
        ]
        for row in dict_rows:
            self.dictwirter.writerow(row) # 写入字段数据 字典 格式

    def __del__(self):
        self.f.close()


if __name__ == '__main__':
    snippet = Snippet()
    snippet.dosomething()